package com.hsgene.user.support;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hsgene.common.util.basic.JsonUtils;
import com.hsgene.common.util.http.HttpRequestUtils;
import com.hsgene.user.support.dto.WeChatSessionResponse;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;

/**
 * 微信登录工具支持类
 *
 * @author wangbing
 * @version 1.0, 2018/10/16
 */
@Component
public class WeChatLoginSupport {

    private final static Logger LOGGER = LoggerFactory.getLogger(WeChatLoginSupport.class);

    /**
     * 接口请求地址
     */
    private final static String WECHAT_API = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 参数格式拼接：grant_type=authorization_code为固定值
     */
    private final static String PARAM_FORMAT = "appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    /**
     * 微信公众平台APP_ID
     */
    @Value("${wechat.platform.public.app_id}")
    private String appId;

    /**
     * 微信公众平台APP_SECRET
     */
    @Value("${wechat.platform.public.app_secret}")
    private String appSecret;

    public WeChatSessionResponse getWechatUser(String code) {
        String params = String.format(PARAM_FORMAT, appId, appSecret, code);
        String requestUrl = WECHAT_API + "?" + params;
        LOGGER.info("Wechat request:" + requestUrl);
        String result = HttpRequestUtils.httpRequest(requestUrl, "GET", null);
        LOGGER.info("Wechat response:" + result);
        return JsonUtils.jsonToObject(result, new TypeReference<WeChatSessionResponse>() {});
    }

    public String decrypt(WeChatSessionResponse sessionResponse, String encryptedData, String iv) {
        return WeChatAesDecryptUtil.decrypt(sessionResponse.getSession_key(), encryptedData, iv);
    }
}
